const app = getApp()

import {NoMusicToast , BGPlayer} from "../../utils/backMusic";

// 创建内部audio上下文 InnerAudioContext 对象
const innerAudioContext = wx.createInnerAudioContext()
const backgroundAudioManager = wx.getBackgroundAudioManager();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    switchFlag: true, // 音频文件自动续播开关标识（false关闭，true开启）
    audioFlag: false, // 音频文件播放标识（false关闭，true开启）
    changeSlider: false, // 用户是否在拖动滑动条
    autoContinue: true, // 是否正在自动续播（false：否，true：是）
    sliderNow: 0, // slider进度条当前进度（slider进度值必须为Number），用来控制音频文件播放位置
    sliderMax: 100, // slider进度条最大值
    playNow: 0, // 音频文件当前播放时间（单位：秒）
    playTimeNow: '00:00', // 音频文件实时播放时间（分钟：秒数），用于页面显示
    duration: '', // 音频文件的总时长（单位：秒）
    durationTime: '', // 音频文件的总时长（分：秒），用于页面显示
    scale: '', // slider滑动条总长度与音频总时长的比例
    articleId: '', // 文章ID
    articleNowIndex: '', // 当前文章的下标
    articleLastIndex: '', // 最后一篇文章的下标
    key_id: '', // 外键ID，获取作业时使用
    activity_id: '', // 活动ID
    company_id: '', // 企业读书活动ID
    classId: '', //六项精进活动ID
    bookInfo: {}, // 书本详情
    type: '', // 作业类型（"sixItem"：六项精进，"company"：企业读书，"student"：塾生学习）
    task: '', // 是否有作业
    articleDetail: '', // 文章详情
    article_text: '', // 文章内容
    taskNavList: '', // 作业导航列表
    collectionStatus: false, // 收藏标识
    collection_id: '', // 收藏ID
    playAudio: false, // 音频播放状态（true: 播放，false: 暂停）
    fontSetSize: 'small', // 用户设置的字体大小（'small'：小，'middle'：中，'large'：大）
    showPopup: false, // 是否打开文章内容弹窗（true: 打开，false: 关闭）
    // "复制按钮"拖拽参数
    writePosition: [15, 60], //默认定位参数
    writesize: [0, 0], // X Y 定位
    window: [0, 0], // 屏幕尺寸
    write: [0, 0], // 定位参数 
    book_id:"" ,
    class_id:"" ,
    book_book_url:"" ,
    book_audio_date:""
  },

  /**
   * 获取文章详情
   */
  getArticleDetails () {
    wx.showLoading({
      title: '加载中',
    })
    let token = wx.getStorageSync('token')
    let articleId = this.data.articleId
    app.http({
      config: {
        url: '/api/User/article_info',
        data: {
          token,
          article_id: articleId
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'articleDetailRes')
      if (res.data.data.collection) {
        this.setData({
          collectionStatus: true,
          collection_id: res.data.data.collection.id
        })
      }
      let articleDetail = res.data.data
      // let article_text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + articleDetail.text.replace(/\r\n/g,"\r\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
      let article_text = articleDetail.text;
      let duration = Number(articleDetail.playtime) // 音频总时长（单位：秒）
      let durationTime = this.timeFormatter(duration) // 音频总时长（分：秒），用于页面显示
      let scale = this.data.sliderMax / duration // slider滑动条总长度与音频总时长的比例
      // console.log('articleDetail', articleDetail)
      // console.log('duration', duration)
      // console.log('durationTime', durationTime)
      // console.log('scale', scale)
      this.setData({
        articleDetail,
        article_text,
        duration,
        durationTime,
        scale,
        book_book_url:res.data.data.article_leader
      })
      // 设置audio的资源地址
      innerAudioContext.src = res.data.data.article_leader

      wx.setNavigationBarTitle({
        title: res.data.data.book.book_title
     });

      wx.hideLoading()
    }).catch(err => {
      console.log(err, 'articleDetailErr')
      wx.hideLoading()
    })
  },

  /**
   * 自动续播功能开启/关闭（之前有这个功能，后面客户要求去掉，改成默认自动续播）
   * @param {*} e 
   */
  handleChangeSwitch (e) {
    this.setData({
      switchFlag: e.detail.value,
      autoContinue: e.detail.value
    })
    // 将自动续播状态存储进本地缓存
    wx.setStorageSync('autoContinue', e.detail.value)
    if (e.detail.value) {
      innerAudioContext.autoplay = true
    }
  },

  /**
   * 用户拖动slider进度条，修改音频文件播放进度
   * @param {slider进度条当前进度值} e 
   */
  handleChangeSlider (e) {
    console.log("用户拖动slider进度条，slider发生change事件，携带值为", e.detail.value)
    let playNow = e.detail.value / this.data.scale // 滑动条当前进度对应的音频播放时间
    let playTimeNow = this.timeFormatter(playNow) // 音频文件实时播放时间（分钟：秒数），用于页面显示
    this.setData({
      sliderNow: e.detail.value,
      playNow,
      playTimeNow,
      changeSlider: true
    })
  },

  /**
   * 用户点击slider进度条，修改音频文件播放进度
   * @param {slider进度条当前进度值} e 
   */
  handleChangeSliderEnd (e) {
    if(NoMusicToast(this.data.book_book_url)) return

    console.log("用户点击slider进度条，slider发生change事件，携带值为", e.detail.value)
    let playNow = e.detail.value / this.data.scale // 滑动条当前进度对应的音频播放时间
    let playTimeNow = this.timeFormatter(playNow) // 音频文件实时播放时间（分钟：秒数），用于页面显示
    this.setData({
      sliderNow: e.detail.value,
      playNow,
      playTimeNow,
      changeSlider: false
    })
    this.playOrPauseAudio(playNow)
  },

  /**
   * 音频播放/暂停
   * @param {音频跳转的位置（单位：秒）} parameter 
   */
  playOrPauseAudio (parameter) {
    if(NoMusicToast(this.data.book_book_url)) return
   
   

    let that = this

    if (that.data.sliderNow < 100) {

      // 判断，当前音频文件播放图标为暂停状态并且用户没有修改slider滑动条进度
      if (!that.data.audioFlag && ((typeof parameter) === 'object')) {

        // 将当前音频文件播放图标为修改为播放状态
        that.setData({
          audioFlag: true,
          autoContinue: true
        })

        // 播放音频文件
        innerAudioContext.play()

      } else if (!that.data.audioFlag && ((typeof parameter) === 'number')) { // 判断，当前音频文件播放图标为暂停状态并且用户修改了slider滑动条进度

        // 音频跳转到指定位置
        innerAudioContext.seek(parameter)

      } else if (that.data.audioFlag && ((typeof parameter) === 'number')) { // 判断，当前音频文件播放图标为播放状态并且用户修改了slider滑动条进度

        // 音频跳转到指定位置
        innerAudioContext.seek(parameter)

      } else {

        // 将当前音频文件播放图标为修改为暂停状态
        that.setData({
          audioFlag: false,
          autoContinue: false
        })

        // 暂停音频播放
        innerAudioContext.pause()
      }

    } else {

      // 将当前音频文件播放图标为修改为播放状态
      that.setData({
        audioFlag: true,
        autoContinue: true
      })

      // 音频跳转到指定位置
      innerAudioContext.seek(0)
    }
  },

  /**
   * 获取企业读书作业
   */
  getCompanyTask () {
    let token = wx.getStorageSync('token')
    let article_id = this.data.articleId
    let key_id = this.data.key_id
    let book_id = this.data.book_id
    app.http({
      config: {
        url: '/api/User/company_read_work',
        data: {
          token,
          article_id ,
          book_id ,
          key_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'companyTaskRes')
      this.setData({
        taskNavList: res.data.data.data
      })
    }).catch(err => {
      console.log(err, 'companyTaskErr')  
    })
  },

  /**
   * 获取六项精进作业
   */
  getSixItemTask () {
    let token = wx.getStorageSync('token')
    let article_id = this.data.articleId
    let key_id = this.data.class_id
    let book_id=this.data.book_id
    let class_id = this.data.class_id
    app.http({
      config: {
        url: '/api/User/personal_read_work',
        data: {
          token,
          key_id:class_id ,
          book_id ,
          article_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'sixItemTaskRes')
      this.setData({
        taskNavList: res.data.data.data
      })
    }).catch(err => {
      console.log(err, 'sixItemTaskErr')
    })
  },

  /**
   * 将秒数转换成“分钟：秒数”的格式
   * @param {时间（秒数）} duration 
   */
  timeFormatter(duration) {
    
    this.setData({
      book_audio_date:duration
    })

    let secondTime = Math.floor(duration); // 秒

    let minuteTime = 0; // 分

    if (secondTime > 60) {

      // 获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);

      // 获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);

    }
    let result = secondTime > 9 ? secondTime : ('0' + secondTime);
    if (minuteTime > 0) {
      result = (minuteTime > 9 ? minuteTime : ('0' + minuteTime)) + ":" + result;
    } else {
      result = "00" + ":" + result;
    }
    return result;
  },

  /**
   * 获取企业读书书本详情
   */
  getCompanyBookInfo () {
    let that = this
    let token = wx.getStorageSync('token')
    // console.log(token)
    app.http({
      config: {
        url: '/api/User/company_read_info',
        data: {
          token,
          company_read_id: that.data.company_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'companyBookInfoRes')
      let bookInfo = res.data.data
      let article = bookInfo.article
      let articleLastIndex = article.length - 1
      article.forEach((item, index) => {
        if (item.id == that.data.articleId) {
          that.setData({
            articleNowIndex: index
          })
        }
      })
      this.setData({
        bookInfo,
        articleLastIndex
      })
    }).catch(err => {
      console.log(err, 'companyBookInfoErr')
    })
  },

  /**
   * 获取六项精进书本详情
   */
  getSixItemBookInfo () {
    let that = this
    let token = wx.getStorageSync('token')
    let class_id = this.data.class_id
    let book_id=this.data.book_id
    app.http({
      config: {
        url: '/api/User/personal_read_info',
        data: {
          token,
          personal_read_id:class_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log( res.data.data, 'activityDetailR111111111111')
      let bookInfo = res.data.data
      let article = bookInfo.article
      let articleLastIndex = article.length - 1
      article.forEach((item, index) => {
        if (item.id == that.data.articleId) {
          that.setData({
            articleNowIndex: index
          })
        }
      })
      this.setData({
        bookInfo,
        articleLastIndex
      })
    }).catch(err => {
      console.log(err, 'activityDetailErr')
    })
  },
  
  // 收藏
  handleCollection () {
    let token = wx.getStorageSync('token')
    let articleId = this.data.articleId
    app.http({
      config: {
        url: '/api/User/create_collection',
        data: {
          token,
          article_id: articleId
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'collectionRes')
      this.getArticleDetails()
      this.setData({
        collectionStatus: true
      })
    }).catch(err => {
      console.log(err, 'collectionErr')
    })
  },

  // 取消收藏
  handleDeleteCollection () {
    let token = wx.getStorageSync('token')
    let collection_id = this.data.collection_id
    app.http({
      config: {
        url: '/api/User/del_collection',
        data: {
          token,
          collection_id
        },
        method: 'POST'
      },
      isAuth: true
    }).then(res => {
      console.log(res, 'deleteCollectionRes')
      this.getArticleDetails()
      this.setData({
        collectionStatus: false
      })
    }).catch(err => {
      console.log(err, 'deleteCollectionErr')
    })
  },

  /**
   * 关闭文章内容弹窗
   */
  handleClosePopup () {
    this.setData({
      showPopup: false
    })
  },

  /**
   * 打开文章内容弹窗
   */
  handleOpenPopup () {
    this.setData({
      showPopup: true
    })
  },

  /**
   * 用户点击"上一节"按钮
   */
  handlePlayLastSection () {
    // 判断，用户开启自动续播，继续执行播放方法
    if (this.data.autoContinue) {
      innerAudioContext.autoplay = true
      let article = ''
      switch (this.data.type) {
        case 'company':
          article = this.data.bookInfo.article
          break;
        case 'student':
          article = this.data.bookInfo.article
          break;
      }
      let articleNowIndex = this.data.articleNowIndex
      if (articleNowIndex > 0) {
        this.setData({
          audioFlag: false,
          sliderNow: 0,
          playNow: 0,
          playTimeNow: '00:00',
        })

        let articleId = article[articleNowIndex - 1].id
        this.setData({
          articleId
        })

        this.getArticleDetails()
        switch (this.data.type) {
          case 'company':
            this.getCompanyBookInfo()
            break;
          case 'student':
            this.getSixItemBookInfo()
            break;
        }
      }
    } else {
      let article = ''
      switch (this.data.type) {
        case 'company':
          article = this.data.bookInfo.article
          break;
        case 'student':
          article = this.data.bookInfo.article
          break;
      }
      let articleNowIndex = this.data.articleNowIndex
      if (articleNowIndex > 0) {
        this.setData({
          audioFlag: false,
          sliderNow: 0,
          playNow: 0,
          playTimeNow: '00:00',
        })

        let articleId = article[articleNowIndex - 1].id
        this.setData({
          articleId
        })

        this.getArticleDetails()
        switch (this.data.type) {
          case 'company':
            this.getCompanyBookInfo()
            break;
          case 'student':
            this.getSixItemBookInfo()
            break;
        }
      }
    }
  },

  /**
   * 用户点击"下一节"按钮
   */
  handlePlayNextSection () {
    // 判断，用户开启自动续播，继续执行播放方法（以前可以选择开启或者关闭自动续播，现在改默认自动续播）
    if (this.data.autoContinue) {
      innerAudioContext.autoplay = true
      let article = ''
      switch (this.data.type) {
        case 'company':
          article = this.data.bookInfo.article
          break;
        case 'student':
          article = this.data.bookInfo.article
          break;
      }
      let articleNowIndex = this.data.articleNowIndex
      let articleLastIndex = this.data.articleLastIndex
      if (articleNowIndex < articleLastIndex) {
        this.setData({
          audioFlag: false,
          sliderNow: 0,
          playNow: 0,
          playTimeNow: '00:00',
        })

        let articleId = article[articleNowIndex + 1].id
        this.setData({
          articleId
        })

        this.getArticleDetails()
        switch (this.data.type) {
          case 'company':
            this.getCompanyBookInfo()
            break;
          case 'student':
            this.getSixItemBookInfo()
            break;
        }
      }
    } else {
      let article = ''
      switch (this.data.type) {
        case 'company':
          article = this.data.bookInfo.article
          break;
        case 'student':
          article = this.data.bookInfo.article
          break;
      }
      let articleNowIndex = this.data.articleNowIndex
      let articleLastIndex = this.data.articleLastIndex
      if (articleNowIndex < articleLastIndex) {
        this.setData({
          audioFlag: false,
          sliderNow: 0,
          playNow: 0,
          playTimeNow: '00:00',
        })

        let articleId = article[articleNowIndex + 1].id
        this.setData({
          articleId
        })

        this.getArticleDetails()
        switch (this.data.type) {
          case 'company':
            this.getCompanyBookInfo()
            break;
          case 'student':
            this.getSixItemBookInfo()
            break;
        }
      }
    }
  },

  /**
   * 打开文章内容弹窗后禁止下面页面滚动
   */
  doNotScroll () {},

  /**
   * 计算默认定位值 
   */ 
  getSysdata () {
    let that = this
    wx.getSystemInfo({
      success (e) {
        let window = [e.windowWidth, e.windowHeight]
        let write = []
        write[0] = that.data.writePosition[0]
        write[1] = that.data.writePosition[1]
        // console.log('write', write)
        that.setData({
          window,
          write,
        }, function () {
          // 获取元素宽高
          wx.createSelectorQuery().select('.open-popup').boundingClientRect(function (res) {
            // console.log(res.width)
            // console.log(res.height)
            let writesize = [res.width, res.height]
            that.setData({
              writesize
            })
          }).exec()
        })
      },
      fail (e) {
        console.log(e)
      }
    })
  },

  /**
   * 开始拖拽 
   */   
  touchmove (e) {
    let that = this
    let positionRight = 0
    if (e.touches[0].clientX < (that.data.writesize[0] / 2)) {
      positionRight = that.data.window[0] - that.data.writesize[0] - 1
    } else {
      if (e.touches[0].clientX > (that.data.window[0] - that.data.writesize[0] / 2)) {
        positionRight = 0
      } else {
        positionRight = that.data.window[0] - e.touches[0].clientX - that.data.writesize[0] / 2
      }
    }
    let positionBottom = 0
    if (e.touches[0].clientY < (that.data.writesize[1] / 2)) {
      positionBottom = that.data.window[1] - that.data.writesize[1]
    } else {
      if (e.touches[0].clientY > (that.data.window[1] - that.data.writesize[1] / 2)) {
        positionBottom = 0
      } else {
        positionBottom = that.data.window[1] - e.touches[0].clientY - that.data.writesize[1] / 2
      }
    }
    let position = [positionRight, positionBottom]
    that.setData({
      write: position
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let book_id = options.bookId //书本id
    let articleId = options.articleId // 文章ID
    let key_id = options.key_id // 外键ID，获取作业时使用
    let type = options.type // 作业类型（"sixItem"：六项精进，"company"：企业读书，"student"：塾生学习）
    let company_id = options.company_id // 企业读书活动ID
    // let classId = options.classId //六项精进活动ID
    let task = options.task // 是否有作业
    let book_name = options.book_name
    let class_id = options.classId
    app.setTitle(book_name)
    this.setData({
      articleId,
      key_id,
      type,
      company_id,
      class_id,
      task,
      book_id
    })
    console.log(class_id , "11111111")

    // 在页面中定义"复制原文"按钮位置
    this.getSysdata()

    this.getArticleDetails()
    switch (type) {
      case 'company':
        this.getCompanyTask()
        this.getCompanyBookInfo()
        break;
      case 'student':
        this.getSixItemTask()
        this.getSixItemBookInfo()
        break;
    }

    // 监听音频播放事件
    innerAudioContext.onPlay(() => {
      this.setData({
        audioFlag: true
      })
    })

    innerAudioContext.onTimeUpdate(() => {
      // 判断，用户是否在拖动进度条准备改变音频播放进度，如果是，则进度条的实时进度更新功能暂停，如果不是，则实时更新进度条进度
      if (!this.data.changeSlider) {

        // 当前音频的播放位置（单位 s）
        let currentTime = innerAudioContext.currentTime
  
        // 当前音频的播放位置（单位：秒）
        let playNow = Math.round(currentTime)
  
        // 当前音频的播放时间（分：秒），用于页面显示
        let playTimeNow = this.timeFormatter(currentTime)
  
        // 让滑动条跟随音频播放进度滑动
        let sliderNow = Math.round(playNow * this.data.scale)
  
        this.setData({
          playNow,
          playTimeNow,
          sliderNow
        })
      }
    })

    // 监听，音频完成跳转
    innerAudioContext.onSeeked(() => {
      // 判断，音频播放图标是暂停状态，完成跳转后要调用pause()暂停音频播放，不然音频完成跳转后会自动播放
      if (!this.data.audioFlag && ((typeof this.data.playNow) === 'number')) {

        // 暂停音频播放
        innerAudioContext.pause()
      } else { // 判断，音频播放图标是播放状态，完成跳转后继续播放

        /**
         * 这里要先调用pause()暂停音频播放，然后用计时器延迟一点时间再播放，不然onTimeUpdate()回调会不执行（小程序API的bug），就无法监听音频的播放进度了
         */
        // 暂停音频播放
        innerAudioContext.pause()

        setTimeout(() => {
          // 播放音频文件
          innerAudioContext.play()
        }, 100)
      }
    })

    // 监听，音频播放结束
    innerAudioContext.onEnded((res) => {

      // 判断，用户开启自动续播，继续执行播放方法（以前可以选择开启或者关闭自动续播，现在改默认自动续播）
      if (this.data.autoContinue) {

        innerAudioContext.autoplay = true
        let article = ''
        switch (this.data.type) {
          case 'company':
            article = this.data.bookInfo.article
            break;
          case 'student':
            article = this.data.bookInfo.article
            break;
        }
        let articleNowIndex = this.data.articleNowIndex
        let articleLastIndex = this.data.articleLastIndex
        console.log('articleNowIndex', articleNowIndex)
        console.log('articleLastIndex', articleLastIndex)
        if (articleNowIndex < articleLastIndex) {
          this.setData({
            audioFlag: false,
            sliderNow: 0,
            playNow: 0,
            playTimeNow: '00:00',
          })

          let articleId = article[articleNowIndex + 1].id
          this.setData({
            articleId
          })

          this.getArticleDetails()
          switch (this.data.type) {
            case 'company':
              this.getCompanyBookInfo()
              break;
            case 'student':
              this.getSixItemBookInfo()
              break;
          }
        } else {
          this.setData({
            audioFlag: false,
            sliderNow: 0,
            playNow: 0,
            playTimeNow: '00:00',
            articleNowIndex: 0,
          })

          let articleId = article[0].id
          this.setData({
            articleId
          })

          this.getArticleDetails()
          switch (this.data.type) {
            case 'company':
              this.getCompanyBookInfo()
              break;
            case 'student':
              this.getSixItemBookInfo()
              break;
          }
        }
      } else {
        this.setData({
          audioFlag: false,
          sliderNow: 100,
          playNow: this.data.duration,
          playTimeNow: this.data.durationTime,
          autoContinue: false
        })
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    backgroundAudioManager.stop()
    let fontSetSize = wx.getStorageSync('fontSetSize') // 本地缓存中用户设置的字体大小
    if (fontSetSize) {
      this.setData({
        fontSetSize
      })
    }

    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    innerAudioContext.autoplay = false
    innerAudioContext.pause()
    this.handleClosePopup()


  

    let data = {
      audioFlag:this.data.audioFlag , 
      book_book_url:this.data.book_book_url ,
      article_title:this.data.articleDetail.article_title ,
      book_title: this.data.articleDetail.book.book_title,
      reader_link:this.data.articleDetail.reader_link, 
      book_logo:this.data.articleDetail.book.book_logo ,
      book_audio_date:this.data.book_audio_date
    }

    BGPlayer(data)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})